package cn.tedu.sp06.fb;

import cn.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class OrderFB implements FallbackProvider {
    @Override
    public String getRoute() {
        /*设置当前降级类，调用哪个后台服务会应用当前降级类*/
        return "order-service";//只针对商品降级
        //return *  对所有服务都降级
        //return null 对所有服务都降级
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        /*降级后给客户端发回的响应数据*/

        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                //响应状态码，提示信息
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                //只返回状态码
                return HttpStatus.INTERNAL_SERVER_ERROR.value();
            }

            @Override
            public String getStatusText() throws IOException {
                //只返回提示状态信息
                return HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();
            }

            @Override
            public void close() {
            //关流使用
            }

            @Override
            public InputStream getBody() throws IOException {
                //响应请求体数据
                String json = JsonResult.err().code(500).msg("访问订单失败").toString();
                /*ByteArrayInputStream流是内存数组的流，不占用底层系统资源，不需要关闭*/
                return new ByteArrayInputStream(json.getBytes("UTF-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
                //响应请求头
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Type", "application/json;charset=UTF-8");
                return headers;
            }
        };
    }
}
